﻿using CodingSeb.ExpressionEvaluator;

using System.Collections.Generic;
using System.Text;

namespace ThingsGateway.Foundation
{
    [System.Security.SecuritySafeCritical]
    public static class ExpressionsHelper
    {
        /// <summary>
        /// 计算变量地址表达式，返回<see cref="IDictionary{TKey, TValue}"/>
        /// </summary>
        /// <param name="expressions"></param>
        /// <returns></returns>
        public static IDictionary<string, object> GetExpressionsResult(this string expressions)
        {
            ExpressionEvaluator evaluator = new ExpressionEvaluator();
            evaluator.Variables = new Dictionary<string, object>()
                {
                  { "DATA".ToUpper(), null},
                  { "TEXT".ToUpper(), null},
                  {"BCD".ToUpper(), null },
                  {"LEN".ToUpper(), (ushort)0 },
                };
            if (expressions.IsNullOrWhiteSpace()) return evaluator.Variables;

            evaluator.Types.Add(typeof(DataFormat));
            evaluator.Types.Add(typeof(Encoding));
            evaluator.Types.Add(typeof(BCDFormat));
            evaluator.OptionCaseSensitiveEvaluationActive = false;
            evaluator.OptionInstanceMethodsCallActive = false;
            evaluator.OptionStaticPropertiesGetActive = true;

            var value = evaluator.ScriptEvaluate(expressions);

            return evaluator.Variables;
        }


        /// <summary>
        /// 计算表达式：raw*100
        /// </summary>
        /// <param name="expressions"></param>
        /// <returns></returns>
        public static object GetExpressionsResult(this ExpressionEvaluator evaluator, string expressions, object rawvalue)
        {
            if (expressions.IsNullOrEmptyEx())
            {
                return rawvalue;
            }
            evaluator.Variables = new Dictionary<string, object>()
                {
                  { "Raw", rawvalue},
                  { "raw", rawvalue},
                };
            var value = evaluator.Evaluate(expressions);
            return value;
        }




    }
}
